package com.yanftch.stopcoding.request;

import com.alibaba.fastjson2.JSONObject;
import com.yanftch.stopcoding.bean.HotBean;
import com.yanftch.stopcoding.cb.RequestCallBack;
import com.yanftch.stopcoding.common.network.CallBack;
import com.yanftch.stopcoding.common.network.HttpUtils;
import com.yanftch.stopcoding.common.util.TextUtils;
import org.jetbrains.annotations.NotNull;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取微博热榜数据
 * 需要分三个接口来调用
 * 参考：@link https://juejin.cn/post/7221046247263322171
 */
public class WeiBoRequest implements Request {

    public interface WeiBoHotCallBack {
        void onSuccess(ArrayList<HotBean> list);

        void onError(Exception e);
    }

    // 热搜 URL
    private static final String WEIBO_HOT_URL = "https://s.weibo.com/top/summary?cate=realtimehot";

    // tid    window.gen_callback && gen_callback({"retcode":20000000,"msg":"succ","data":{"tid":"01Ab5o_NJk8VP9OJ7D7a599FFdKWrwZFOxk-0bjhAVksXE","new_tid":true}});
    private static final String WEIBO_TID_URL = "https://passport.weibo.com/visitor/genvisitor?cb=gen_callback";

    // cookie   https://passport.weibo.com/visitor/visitor?a=incarnate&t=%E6%8E%A5%E5%8F%A31%E9%87%8C%E7%9A%84tid&w=3&c=100&cb=cross_domain&from=weibo
    private static final String WEIBO_SUB_URL = "https://passport.weibo.com/visitor/visitor?a=incarnate&t=";
    private static final String WEIBO_SUB_URL_PREFIX = "&w=3&c=100&cb=cross_domain&from=weibo";

    @Override
    public void request(RequestCallBack callBack) {
        getWeiboHotList(new WeiBoHotCallBack() {
            @Override
            public void onSuccess(ArrayList<HotBean> list) {
                if (callBack != null)
                    callBack.onSuccess(list);
            }

            @Override
            public void onError(Exception e) {
                if (callBack != null)
                    callBack.onError(e);
            }
        });
    }

    private void getWeiboHotList(@NotNull WeiBoHotCallBack weiBoHotCallBack) {
        getWeiboTid(new CallBack() {
            @Override
            public void onSuccess(String response) {
                if (TextUtils.isEmpty(response)) {
                    weiBoHotCallBack.onError(new Exception("response is empty"));
                    return;
                }
                String tid = "";
                try {
                    // 获取 tid
                    // // window.gen_callback && gen_callback({"retcode":20000000,"msg":"succ","data":{"tid":"01Ab5o_NJk8VP9OJ7D7a599FFdKWrwZFOxk-0bjhAVksXE","new_tid":true}});
                    String quStr = response.substring(response.indexOf("(") + 1, response.indexOf(")"));
                    if (!TextUtils.isEmpty(quStr)) {
                        JSONObject jsonObject = JSONObject.parseObject(quStr);
                        if (jsonObject.getIntValue("retcode") == 20000000) {
                            tid = jsonObject.getJSONObject("data").getString("tid");
                        }
                    }
                } catch (Exception e) {
                    tid = "";
                    weiBoHotCallBack.onError(new Exception("微博API路径变了，找插件开发者更新吧~"));
                }
                if (!TextUtils.isEmpty(tid)) {
                    getWeiboSub(tid, new CallBack() {
                        @Override
                        public void onSuccess(String response) {
                            if (TextUtils.isEmpty(response)) {
                                weiBoHotCallBack.onError(new Exception("response is empty"));
                                return;
                            }
                            String sub = "";
                            String subp = "";
                            try {
                                // // window.cross_domain && cross_domain({"retcode":20000000,"msg":"succ","data":{"sub":"_2AkMQUXTgf8NxqwFRmf4VzGnkaI1zzQHEieKmDYU7JRMxHRl-yT9kqkhStRB6O9FaD1cEwKM32NnxNptG8A2i-2KTP4T9","subp":"0033WrSXqPxfM72-Ws9jqgMF55529P9D9WWhnThkBXkehJIPX9Op.1Lh"}});
                                String quStr2 = response.substring(response.indexOf("(") + 1, response.indexOf(")"));
                                if (!TextUtils.isEmpty(quStr2)) {
                                    JSONObject jsonObject = JSONObject.parseObject(quStr2);
                                    if (jsonObject.getIntValue("retcode") == 20000000) {
                                        sub = jsonObject.getJSONObject("data").getString("sub");
                                        subp = jsonObject.getJSONObject("data").getString("subp");
                                    }
                                }

                                if (!TextUtils.isEmpty(sub) && !TextUtils.isEmpty(subp)) {
                                    Map<String, String> header = new HashMap<>();
                                    header.put("Cookie", "SUB=" + sub + ";SUBP=" + subp);
                                    HttpUtils.setHeaders(header);
                                    HttpUtils.get(WEIBO_HOT_URL, new CallBack() {
                                        @Override
                                        public void onSuccess(String response) {
                                            if (TextUtils.isEmpty(response)) {
                                                weiBoHotCallBack.onError(new Exception("response is empty"));
                                                return;
                                            }
                                            ArrayList<HotBean> list = new ArrayList<>();
                                            Document document = Jsoup.parse(response);
                                            Element item = document.getElementsByTag("tbody").first();
                                            if (item != null) {
                                                Elements items = item.getElementsByTag("tr");
                                                for (Element tmp : items) {
                                                    Element rankEle = tmp.getElementsByTag("td").first();
                                                    Elements textEle = tmp.select(".td-02").select("a");
                                                    Elements tagEle = tmp.select(".td-03");
                                                    Elements rdEle = tmp.select(".td-02").select("span");
                                                    String url = "https://s.weibo.com/" + textEle.attr("href");
//                                                    System.out.println("textEle=" + textEle.text() + ", tagEle=" + tagEle.text() + ", rdEle=" + rdEle.text() + ", url=" + url);
                                                    HotBean bean = new HotBean();
                                                    bean.setTitle(textEle.text());
                                                    bean.setTag(tagEle.text());
                                                    bean.setUrl(url);
                                                    list.add(bean);
                                                }

                                                weiBoHotCallBack.onSuccess(list);
                                            } else {
                                                weiBoHotCallBack.onError(new Exception("微博API路径变了，找插件开发者更新吧~"));
                                            }
                                        }

                                        @Override
                                        public void onError(Exception e) {
                                            weiBoHotCallBack.onError(new Exception("微博API路径变了，找插件开发者更新吧~"));
                                        }
                                    });
                                }

                            } catch (Exception e) {
                                weiBoHotCallBack.onError(new Exception("微博API路径变了，找插件开发者更新吧~"));
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            weiBoHotCallBack.onError(e);
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                weiBoHotCallBack.onError(e);
            }
        });

    }

    private static void getWeiboTid(CallBack callBack) {
        HttpUtils.get(WEIBO_TID_URL, callBack);
    }

    private static void getWeiboSub(String tid, CallBack callBack) {
        HttpUtils.get(WEIBO_SUB_URL + tid + WEIBO_SUB_URL_PREFIX, callBack);
    }

    public static void main(String[] args) {
//        getWeiboHotList(new WeiBoHotCallBack() {
//            @Override
//            public void onSuccess(ArrayList<HotBean> response) {
//
//                for (HotBean bean : response) {
//                    System.out.println(bean);
//                }
//            }
//
//            @Override
//            public void onError(Exception e) {
//
//            }
//        });
    }

}
